<?php
namespace app\admin\controller;
use app\service\apiinvoiceService;
use app\service\billService;
use app\service\invoiceService;
use invoice\Api;
use invoice\Api as InvoiceApi;
use think\Controller;
use think\facade\Db;
use think\facade\Log;
use think\queue\Job;

class Yzltest extends Controller{
    public function test(){

        $id=218286;
        $res=$this->invoiceData($id);
        echo "<pre>";
        var_dump($res);

    }
    public function test1(){
        $id=218388;
        $data=Db::table("billpay")->where("id",$id)->find();


        $invoice=$this->invoiceCreate($data);
        //////echo "<pre>";
        //var_dump($invoice);die;

        if($invoice["errorCode"]=="0"){


            $info=$this->invoiceData($data["id"]);
            echo "<pre>";
            //var_dump($info);
            $api=new apiinvoiceService();
            $res=$api->invoiceSendDirect(json_encode($info));


            var_dump($res);

        }



    }

    public function doInvoiceJob($data){
        $invoice=$this->invoiceCreate($data);

        if($invoice["errorCode"]=="0"){
            $info=$this->invoiceData($data["id"]);
            $api=new apiinvoiceService();
            $res=$api->invoiceSendDirect(json_encode($info));
            return $res;

        }else{
            return false;
        }
    }
    public function invoiceData($id){


        $billpayorder=Db::table("billpay")->where("id",$id)->find();
        $billinvoice=Db::table("billinvoice")->where("pay_id",$id)->where("ctype","1")->find();
        $communityinfo=Db::table("community")->where("community_id",$billinvoice["community_id"])->field("property_id,community_name")->find();

        //根据物业查询发票信息

        $serviceinfo=(new invoiceService())->propertyInvoice($communityinfo["property_id"]);
        //return $serviceinfo;
        //var_dump($info);
        $data["m_short_name"]=$serviceinfo["m_short_name"];
        $data["sub_m_short_name"]=$serviceinfo["sub_m_short_name"];
        $data["user_id"]=$billinvoice["userid"];


        $data["invoice_date"]=$billinvoice["invoice_date"];

        var_dump($billinvoice["billid"]);
        $billid=unserialize($billinvoice["billid"]);
        var_dump($billid);
        $item=array();
        $tax_money=0;
        foreach ($billid as $key =>$value){
            $billinfo = (new billService())->billIdinfo($value);


            $taxrate = (new billService())->taxRateCommunity($billinfo['cost_type'],$billinfo['community_id']);
            if(empty($taxrate)){
                $taxrate ="0.06";
            }
            //$tax_amount=round($taxrate*$billinfo["bill_entry_amount"],2);
            $tax_amount=round(($billinfo["bill_entry_amount"]*$taxrate)/(1+$taxrate),2);
            $tax_money=round($tax_money+$tax_amount,2);
            //$item_ex_tax_amount=$billinfo["bill_entry_amount"];
            //$item_sum_amount=$billinfo["bill_entry_amount"]+$tax_amount;

            $item_ex_tax_amount=$billinfo["bill_entry_amount"]-$tax_amount;
            $item_sum_amount=$billinfo["bill_entry_amount"];
            $item[]="{" .
                " \"item_name\":\"".$billinfo["cost_type"]."\"," .
                "\"item_no\":\"".$billinfo["bill_entry_id"]."\"," .
                "\"item_spec\":\"1\"," .
                "\"item_unit\":\"条\"," .
                "\"item_quantity\":\"1\"," .
                "\"item_unit_price\":\"".$item_ex_tax_amount."\"," .
                "\"item_ex_tax_amount\":\"".$item_ex_tax_amount."\"," .
                "\"item_tax_rate\":\"".$taxrate."\"," .
                "\"item_tax_amount\":\"".$tax_amount."\"," .
                "\"item_sum_amount\":\"".$item_sum_amount."\"," .
                "\"row_type\":\"0\"" .
                "}";

        }

        $data["item"] = implode(',', $item);


//        $data["ex_tax_amount"]=$billinvoice["pay_money"];
//        $data["tax_amount"]=$tax_money;//合计税额，票面上的合计税额
//        $data["sum_amount"]=$billinvoice["pay_money"]+$tax_money;//不含税金额
        $data["ex_tax_amount"]=$billinvoice["pay_money"]-$tax_money;
        $data["tax_amount"]=$tax_money;//合计税额，票面上的合计税额
        $data["sum_amount"]=$billinvoice["pay_money"];//不含税金额
        $data["out_trade_no"]=$billpayorder["out_trade_no"];
        $data["invoice_type"]='BLUE';
        $data["invoice_kind"]='PLAIN';

        $data["invoice_code"]=$billinvoice["invoiceCode"];//发票代码，该字段与invoice_no构成一张发票的唯一标识
        $data["invoice_no"]=$billinvoice["invoiceNum"];//发票号码，该字段与invoice_code构成一张发票的唯一标识。
        //购买方信息
        //$roominfo=Db::table("billinvoice")->where("out_room_id",$billinvoice["out_room_id"])->find();
        $roominfo=Db::table("roominfo")->where("out_room_id",$billinvoice["out_room_id"])->find();
        $data["title_name"]=$communityinfo["community_name"]."-".$roominfo["group"]."-".$roominfo["building"]."-".$roominfo["unit"]."-".$roominfo["room"];
        $data["payer_register_no"]="";//购方税号
        $data["payer_address_tel"]="";
        $data["payer_bank_name_account"]="";

        //销售方信息 根据停车场查询
        $data["payee_register_no"]=$serviceinfo["fp_saler_tax_num"];
        $data["payee_register_name"]=$serviceinfo["name"];
        $data["payee_address_tel"]=$serviceinfo["fp_saler_account"];

        $data["payee_bank_name_account"]=$serviceinfo["bank"];
        $data["check_code"]='';
        //$data["out_invoice_id"]=$info["orderNo"];
        $data["out_invoice_id"]=date("YmdHis").rand(100000,999999);
        $data["ori_blue_inv_code"]='';
        $data["ori_blue_inv_no"]='';
        $data["file_download_type"]='PDF';
        $data["file_download_url"]=$billinvoice["invoiceFileUrl"];
        $data["payee"]='';
        $data["checker"]='';
        $data["clerk"]='';
        $data["invoice_memo"]="物业缴费";
        $data["xtend_fields"]='';
        return $data;

    }
    public function invoiceCreate($data){
        $id=$data["id"];
        $billpayorder=Db::table('billpay')->where("id",$id)->find();
        //查询该账单是否已经开票
        $invoiceinfo=Db::table("billinvoice")->where("pay_id",$id)->where("ctype","1")->find();
        if(!empty($invoiceinfo)){
            $res=$this->CheckEInvoice($invoiceinfo["id"]);

            return $res;
        }
        //更改账单状态
        $billid=unserialize($billpayorder["billid"]);

        $taxmoney=0;
        $invoiceDetail=array();
        foreach ($billid as $key => $value) {
            $billinfo = (new billService())->billIdinfo($value);

            //die;
            $out_room_id[] = $billinfo['out_room_id'];
            $bill_entry_amount=$billinfo['bill_entry_amount'];
            //根据费用类型查询税率
            $taxrate = (new billService())->taxRateCommunity($billinfo['cost_type'],$billinfo['community_id']);
            if(empty($taxrate)){
                $taxrate=0.06;
            }
            $goodsCode=(new billService())->goodsCodeCommunity($billinfo['cost_type'],$billinfo['community_id']);
            if(empty($goodsCode)){
                $goodsCode='';
            }


            $costTypeInfo=(new billService())->getCostTypeInfo($billinfo['cost_type'],$billinfo['community_id']);

            $tax = $billinfo['bill_entry_amount']*$taxrate;
            $taxmoney=$tax+$taxmoney;

            //$inf['cost_type']="物业费";

            $invoiceDetail[] = "{\"goodsName\":\"{$billinfo['cost_type']}\",\"specType\":\"{$billinfo['acct_period']}\",\"unit\":\"期\",\"num\":\"1\",\"price\":\"{$bill_entry_amount}\",\"withTaxFlag\":\"1\",\"taxRate\":\"{$taxrate}\",\"tax\":\"{$tax}\",\"goodsCode\":\"{$goodsCode}\",\"favouredPolicyFlag\":\"{$costTypeInfo['favouredPolicyFlag']}\"}";
            $remark[] = '支付宝支付';
        }




        //根据小区id查询开票信息
        $communityinfo=Db::table('community')->where('community_id',$billpayorder["community_id"])->field("community_name,property_id")->find();
        $propertyinfo=Db::table('property')->where('id',$communityinfo["property_id"])->find();
        $serviceinfo=Db::table('service')->where('id',$propertyinfo["service_id"])->find();




        $money=$billpayorder["pay_money"];
        //税率



        $timestmp = time();
        $remark=$communityinfo["community_name"]."-支付宝支付";
        //判断access_token是否到期
        $second = time()-strtotime($serviceinfo['fp_expires_in']);

//        if($second <86400){
//            //未过期
//            $access_token = $serviceinfo['fp_access_token'];
//        }else{
//
//            //过期从新获取
//            //$access_token = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
//            $res = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
//            $res=json_decode($res,true);
//            if($res["errCode"]=="0"){
//                $access_token=$res["fp_access_token"];
//            }else{
//                $res2["errorCode"]="1";
//                $res2["error"]= $res['errormsg'];
//                return $res2;
//            }
//
//        }
//        $appKey = $serviceinfo["fp_app_key"];
//        $appSecret = $serviceinfo["fp_app_secret"];
//        $token = $access_token;// please store the token and refresh it before expired

        $invoiceConfig=(new invoiceService())->getInvoiceConfig($serviceinfo);
        if($invoiceConfig["errCode"]!='0'){
            $res2["errorCode"]="1";
            $res2["error"]= $invoiceConfig["errMsg"];
            return $res2;
        }
        $appKey = $invoiceConfig["appKey"];
        $appSecret = $invoiceConfig["appSecret"];
        $token = $invoiceConfig["token"];//

        $taxnum = $serviceinfo["fp_saler_tax_num"];

        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        //$method = "nuonuo.electronInvoice.requestBilling"; // change to your method
        $method=$invoiceConfig["method"];
        $senid = uniqid(); // generate your meaningful senid

        $invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = date("YmdHis").rand(100000,999999);
        $timestmp = time();
        $roominfo=Db::table("roominfo")->where("out_room_id",$billpayorder["out_room_id"])->find();
        $invoiceDetail = implode(',', $invoiceDetail);
        $buyerName=$communityinfo["community_name"]."-".$roominfo["group"]."-".$roominfo["building"]."-".$roominfo["unit"]."-".$roominfo["room"];
        //$buyerPhone=$roominfo["owner_phone"];
        $buyerPhone="1";


        $buyerTaxNum="";
        $buyerTel="";
        $buyerAddress="";
        $buyerAccount="";


        $fp_saler_tax_num=$serviceinfo['fp_saler_tax_num'];
        $salerAddress=$serviceinfo['address'];
        $salerTel=$serviceinfo['phone'];
        $salerAddress=$serviceinfo['address'];
        $salerAccount=$serviceinfo['fp_saler_account'];
        $emt="";

        //var_dump($content);
        $body = "{
        \"order\": {
            \"buyerName\": \"$buyerName\",
            \"orderNo\": \"$orderNo\",
            \"buyerTaxNum\": \"$buyerTaxNum\",
            \"buyerTel\": \"$buyerTel\",
            \"buyerAddress\": \"$buyerAddress\",
            \"buyerAccount\": \"$buyerAccount\",
            \"invoiceDate\": \"$invoiceDate\",
            \"clerk\": \"\",
            \"salerTaxNum\": \"$fp_saler_tax_num\",
            \"salerTel\": \"$salerTel\",
            \"salerAddress\": \"$salerAddress\",
            \"salerAccount\": \"$salerAccount\",
            \"invoiceType\": \"1\",
            \"invoiceLine\": \"pc\",
            \"pushMode\": \"1\",
            \"buyerPhone\": \"$buyerPhone\",
            \"remark\": \"$remark\",
            \"invoiceDetail\": [$invoiceDetail],
            \"callBackUrl\": \"http://www.jfzhiwen.com/admin/invoice/callback/\"
            }
        }";

        $result = InvoiceApi::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);

        //var_dump($result);
        $result = json_decode($result, true);

        //Log::write($result,"invoiceresult");
        if($result['code'] == 'E0000'){
            $invoice["invoice_serial_num"] = $result['result']['invoiceSerialNum'];
            $invoice["invoice_time"]=date('Y-m-d H:i:s');
            $invoice["invoice_type"]="1";
            $invoice["invoice_date"]=date('Y-m-d');
            $invoice["billid"]=$billpayorder["billid"];
            $invoice["community_id"]=$billpayorder["community_id"];
            $invoice["out_room_id"]=$billpayorder["out_room_id"];
            $invoice["ctype"]="1";
            $invoice["pay_id"]=$billpayorder["id"];
            $invoice["userid"]=$billpayorder["user_id"];
            $invoice["orderNo"]=$orderNo;
            $invoice["pay_money"]=$billpayorder["pay_money"];
            $id=Db::table("billinvoice")->insertGetId($invoice);
            $res=$this->CheckEInvoice($id);
            return $res;

        }else{
            $res["errorCode"]="1";
            $res["error"]= "发票".$result['describe'];
            return $res;
        }
    }

    //查询发票
    public function CheckEInvoice($id){
        //sleep(20);
        //查询发票序列号
        $data=Db::table('billinvoice')->find($id);

        if(!empty($data["invoiceFileUrl"])){

            $data["errorCode"]="0";
            return $data;

        }
        //根据商家id查询开票信息
        $communityinfo=Db::table("community")->where('community_id',$data["community_id"])->field("property_id")->find();
        $propertyinfo=Db::table('property')->where('id',$communityinfo["property_id"])->field("service_id")->find();
        $serviceinfo=Db::table('service')->where('id',$propertyinfo["service_id"])->find();

        //判断access_token是否到期
//        $second = time()-strtotime($serviceinfo['fp_expires_in']);
//        if($second <86400){
//            //未过期
//            $access_token = $serviceinfo['fp_access_token'];
//        }else{
//            //过期从新获取
//            //$access_token = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
//            $res = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
//            $res=json_decode($res,true);
//            if($res["errCode"]=="0"){
//                $access_token=$res["fp_access_token"];
//            }else{
//                $res2["errorCode"]="1";
//                $res2["error"]= $res['errormsg'];
//                return $res2;
//            }
//        }
//        //var_dump($access_token);die;
//        $timestmp = time();
//        $appKey = $serviceinfo["fp_app_key"];
//        $appSecret = $serviceinfo["fp_app_secret"];
//        $token = $access_token;// please store the token and refresh it before expired

        $invoiceConfig=(new invoiceService())->getInvoiceConfig($serviceinfo);
        if($invoiceConfig["errCode"]!='0'){
            $res2["errorCode"]="1";
            $res2["error"]= $invoiceConfig["errMsg"];
            return $res2;
        }
        $appKey = $invoiceConfig["appKey"];
        $appSecret = $invoiceConfig["appSecret"];
        $token = $invoiceConfig["token"];//


        $taxnum = $serviceinfo["fp_saler_tax_num"];

        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        $method = $invoiceConfig["queryInvoiceMethod"]; // change to your method
        $senid = uniqid(); // generate your meaningful senid
        $body = json_encode(
            array(
                "invoiceSerialNum" => array($data['invoice_serial_num'])
            )
        );

        if($serviceinfo["fp_version"]=="v2"){
            $body = json_encode(
                array(
                    "serialNos" => array($data['invoice_serial_num'])
                )
            );
        }
        $result = InvoiceApi::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
        //print("<error> ".var_export($result,true)."</error> \n");


        $result = json_decode($result, true);
        //echo "<pre>";
        //var_dump($result);exit();
        if($result['code'] == 'E0000'){

            $invoiceCode=$result["result"][0]['invoiceCode'];
            if(isset($result["result"][0]['invoiceNo'])){
                $invoiceNum=$result["result"][0]['invoiceNo'];
            }else if(isset($result["result"][0]['invoiceNum'])){
                $invoiceNum=$result["result"][0]['invoiceNum'];
            }


            $invoiceFileUrl="";
            if(isset($result["result"][0]['invoiceFileUrl'])){
                $invoiceFileUrl=$result["result"][0]['invoiceFileUrl'];
            }else if(isset($result["result"][0]['pdfUrl'])){
                $invoiceFileUrl=$result["result"][0]['pdfUrl'];
            }

            Db::table("billinvoice")
                ->where('id',$id)
                ->update([
                    "invoiceFileUrl"=>$invoiceFileUrl,
                    "invoiceNum"=>$invoiceNum,
                    "invoiceCode"=>$invoiceCode
                ]);
            //更新账单的发票
            $billid=unserialize($data["billid"]);
            foreach ($billid as $key => $value) {
                Db::table("bill")
                    ->where('id',$value)
                    ->update([
                        "invoiceFileUrl"=>$invoiceFileUrl,
                        "invoiceNum"=>$invoiceNum,
                        "invoiceCode"=>$invoiceCode,
                        "invoice_serial_num"=>$data["invoice_serial_num"],
                        "invoice_type"=>1,
                        "invoiceTime"=>time()
                    ]);
            }
            $res=Db::table("billinvoice")->where('id',$id)->find();
            $res["errorCode"]="0";
            return $res;
        }else{
            $res["errorCode"]="1";
            $res["error"]= "发票查询".$result['describe'];
            return $res;

        }
    }

    //当access_token超时时，获取access_token
    public function accessToken($client_id,$client_secret){

        $res = InvoiceApi::getMerchantToken($client_id, $client_secret);

        $tmpInfo = json_decode($res);


        if(property_exists($tmpInfo,'error')){
            //var_dump($tmpInfo);die;
            Log::error("access_token获取失败");
            return json_encode(["errCode"=>"error","errormsg"=>$tmpInfo->error_description]);
            return $tmpInfo;
            //$this->error($tmpInfo->error.',access_token获取失败');
        }
        $data['fp_access_token'] = $tmpInfo->access_token;//获取access_token

        $data['fp_expires_in'] = date('Y-m-d H:i:s',time());

        //$data['id'] = (new billService())->serviceFpAppKey($client_id);
        $id = (new billService())->serviceFpAppKey($client_id);
        //存储access_token

        //$result = (new billService())->serviceUpdate($data);
        Db::table('service')->where("id",$id)->update($data);
        return json_encode(["errCode"=>"0","fp_access_token"=>$data['fp_access_token']]);
        return $data['fp_access_token'];
        // $tmpInfo = '{"access_token":"10ffd45208fb4464aa6fee00vthjozss","expires_in":86400}';

    }
}